package com.剑指offer.第二章;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 三数之和等于0 {

    public static List<List<Integer>> resolve(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (nums.length >= 3) {
            Arrays.sort(nums);
            int i = 0;
            while (i < nums.length - 2) {
                towNum(nums, i, res);
                int temp = nums[i];
                while (nums[i] == temp && i < nums.length) {
                    i++;
                }
            }
        }
        return res;
    }

    public static void towNum(int[] nums, int i, List<List<Integer>> res) {
        int j = i + 1;
        int k = nums.length - 1;

        while (j < k) {
            if (nums[i] + nums[j] + nums[k] == 0) {
                res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                int temp = nums[j];
                while (nums[j] == temp && j < k) {
                    j++;
                }
            } else if (nums[i] + nums[j] + nums[k] > 0) {
                k--;
            } else {
                j++;
            }
        }

    }

    public static void main(String[] args) {

    }

}
